from typing import Generator, Any
from urllib.parse import unquote


def params_str(params: dict):
    s = ""
    for k, v in params.items():
        s += k + "=" + str(v)
        s += "&"
    return s[:-1]


def parser_params(url: str) -> Generator[Any, Any, None] | dict[Any, Any]:
    cookies = {}
    param = url.split('?')
    if len(param) > 1:
        for i in param[1].split('&'):
            v = i.split('=')
            if len(v) > 1:
                cookies[v[0].strip()] = ''.join(v[1:])
    return cookies


def parser_cookie(str_cookies: str, *keys) -> Generator[Any, Any, None] | dict[Any, Any]:
    """
    通过cookies获取指定key值
    args: 需要的key
    :param str_cookies:
    :param keys:
    :return:
    """
    cookies = {}
    for i in str_cookies.split(';'):
        if i:
            v = i.split('=')
            if len(v) > 1:
                cookies[v[0].strip()] = ''.join(v[1:])
    if keys:
        return (cookies[key] for key in keys)
    return cookies


def url_unquote_paser(code):
    """
    url解码 在进行 unquote解码
    """
    if code is None:
        return ""
    return unquote(code, encoding='utf-8').encode("utf-8").decode("unicode_escape")
